const { getList, getDetail, newBlog, updateBlog, delBlog } = require("../controler/blog")
const { SuccessModel, ErrorModel } = require("../model/resModel")
const handleBlogRouter = (req, res) => {
  const method = req.method
  const url = req.url
  const path = url.split('?')[0]
  if (method === 'GET' && path === '/api/blog/list') {
    const { author = '', keyword = '' } = req.query
    let result = getList(author, keyword)
    return result.then(res => {
      return new SuccessModel(res)
    }).catch((err) => {
      console.log('error')
      return new ErrorModel({}, err)
    })
  }
  if (method === 'GET' && path === '/api/blog/detail') {
    let result = getDetail(req.query.id)
    if (!result) {
      return new ErrorModel({}, '请传入ID')
    }
    return result.then(res => {
      return new SuccessModel(res)
    }).catch((err) => {
      return new ErrorModel({}, err)
    })
  }
  if (method === 'GET' && path === '/api/blog/delete') {
    const result = delBlog(req.query.id)
    return result.then((res) => {
      if (res.affectedRows > 0) {
        return new SuccessModel({})
      } else {
        return new ErrorModel({}, `删除失败`)
      }
    })
    // if (result) {
    //   return new SuccessModel(result)
    // } else {
    //   return new ErrorModel({}, '删除失败')
    // }
  }
  if (method === 'POST' && path === '/api/blog/new') {
    let result = newBlog(req.body)
    return result.then((res) => {
      return new SuccessModel({ id: res.insertId})
    }).catch((err) => {
      return new ErrorModel({}, err)
    })
  }
  if (method === 'POST' && path === '/api/blog/update') {
    const result = updateBlog(req.query.id, req.body)
    return result.then((res) => {
      if (res.affectedRows > 0) {
        return new SuccessModel({ id: req.query.id })
      } else {
        return new ErrorModel({}, `更新失败`)
      }
      
    }).catch((err) => {
      return new ErrorModel({}, `${err}`)
    })
  }
}
module.exports = handleBlogRouter